/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package pe.edu.uch.syscom.managedbeans;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.faces.event.ActionEvent;
import javax.faces.model.SelectItem;
import org.apache.log4j.Logger;
import pe.edu.uch.syscom.managedbeans.uibeans.UIClienteBean;
import pe.edu.uch.syscom.mapping.TbCliente;
import pe.edu.uch.syscom.mapping.TbDistrito;
import pe.edu.uch.syscom.utils.CommonDAO;
import pe.edu.uch.syscom.utils.CommonWeb;

/**
 *
 * @author Jose Tejada
 */
public class ClienteMB implements Serializable {

    private static final long serialVersionUID = 1L;
    private final static Logger m_log = Logger.getLogger( ClienteMB.class );
    private String m_sCampoBusqueda;
    private String m_sOncomplete;
    private String m_sDepartamento;
    private String m_sProvincia;
    private List<UIClienteBean> m_lstUIClientes = new ArrayList<UIClienteBean>();
    private SelectItem[] m_cboDepartamentos;
    private SelectItem[] m_cboProvincias;
    private SelectItem[] m_cboDistritos;
    private TbCliente m_tbCliente;

    public ClienteMB() {
        m_log.info( "[ClienteMB] << Enter" );
        m_cboDepartamentos = new SelectItem[ 1 ];
        m_cboDepartamentos[0] = new SelectItem( "000000", "[Seleccione Departamento]" );
        m_cboProvincias = new SelectItem[ 1 ];
        m_cboProvincias[0] = new SelectItem( "000000", "[Seleccione Provincia]" );

        m_tbCliente = new TbCliente();

        m_log.info( "[ClienteMB] >> Exit" );
    }

    public TbCliente getTbCliente() {
        return m_tbCliente;
    }

    public void setTbCliente( TbCliente tbCliente ) {
        m_tbCliente = tbCliente;
    }

    public String getCampoBusqueda() {
        return m_sCampoBusqueda;
    }

    public void setCampoBusqueda( String sCampoBusqueda ) {
        m_sCampoBusqueda = sCampoBusqueda;
    }

    public String getOncomplete() {
        return m_sOncomplete;
    }

    public void setOncomplete( String sOncomplete ) {
        m_sOncomplete = sOncomplete;
    }

    public List<UIClienteBean> getLstClientes() {
        m_log.info( "[getLstClientes] << Enter" );
        int iSizeClientes;
        UIClienteBean uiCliente;
        TbCliente tbCliente;
        List<TbCliente> lstClientes;
        m_lstUIClientes = new ArrayList<UIClienteBean>();
        try {

            lstClientes = CommonDAO.getTbClienteDAO().loadListaClientes( m_sCampoBusqueda );

            iSizeClientes = lstClientes.size();
            for ( int i = 0; i < iSizeClientes; i++ ) {
                tbCliente = lstClientes.get( i );

                uiCliente = new UIClienteBean();
                uiCliente.convertir( i + 1, tbCliente );
                m_lstUIClientes.add( uiCliente );
            }
        } catch ( Exception ex ) {
            m_log.error( "EX " + ex );
            m_log.error( "EX " + ex.getMessage() );
            ex.printStackTrace();
        }
        m_log.info( "[getLstClientes] << Exit" );
        return m_lstUIClientes;
    }

    public void setLstClientes( List<UIClienteBean> lstClientes ) {
        m_log.info( "[setLstClientes] << Enter" );
        m_lstUIClientes = lstClientes;
        m_log.info( "[setLstClientes] >> Exit" );
    }

    public SelectItem[] getCboDepartamentos() {
        m_log.info( "[getCboDepartamentos] << Enter" );
        int iSizeDep;
        TbDistrito dep;
        List<TbDistrito> lstDepartamentos;
        m_cboDepartamentos = new SelectItem[ 0 ];
        try {
            lstDepartamentos = CommonDAO.getTbDistritoDAO().loadDepartamentos();

            m_cboDepartamentos = new SelectItem[ lstDepartamentos.size() ];
            iSizeDep = lstDepartamentos.size();
            for ( int i = 0; i < iSizeDep; i++ ) {
                dep = lstDepartamentos.get( i );

                m_cboDepartamentos[ i] = new SelectItem( dep.getDisCod(), dep.getDisDes() );
            }
        } catch ( Exception ex ) {
            m_log.error( "EX " + ex );
            m_log.error( "EX " + ex.getMessage() );
            ex.printStackTrace();
        }
        m_log.info( "[getCboDepartamentos] >> Exit" );
        return m_cboDepartamentos;
    }

    public void setCboDepartamentos( SelectItem[] cboDepartamentos ) {
        m_log.info( "[setCboDepartamentos] << Enter" );
        m_cboDepartamentos = cboDepartamentos;
        m_log.info( "[setCboDepartamentos] >> Exit" );
    }

    public SelectItem[] getCboProvincias() {
        m_log.info( "[getCboProvincias] << Enter" );
        int iSizeProv = 0;
        TbDistrito prov;
        List<TbDistrito> lstProvincias;

        m_cboProvincias = new SelectItem[ 1 ];
        try {
            if ( m_sDepartamento != null && !m_sDepartamento.isEmpty() && !m_sDepartamento.equals( "000000" ) ) {
                lstProvincias = CommonDAO.getTbDistritoDAO().loadProvincias( m_sDepartamento );

                iSizeProv = lstProvincias.size();
                m_cboProvincias = new SelectItem[ iSizeProv + 1 ];
                for ( int i = 0; i < iSizeProv; i++ ) {
                    prov = lstProvincias.get( i );
                    m_cboProvincias[ i + 1] = new SelectItem( prov.getDisCod(), prov.getDisDes() );
                }
            }
        } catch ( Exception ex ) {
            m_log.error( "EX " + ex );
            m_log.error( "EX " + ex.getMessage() );
            ex.printStackTrace();
        } finally {
            if ( iSizeProv == 0 ) {
                m_cboProvincias = new SelectItem[ 1 ];
            }
            m_cboProvincias[0] = new SelectItem( "000000", "[Seleccione Provincia]" );
        }
        m_log.info( "[getCboProvincias] >> Exit" );
        return m_cboProvincias;
    }

    public void setCboProvincias( SelectItem[] cboProvincias ) {
        m_log.info( "[setCboProvincias] << Enter" );
        m_cboProvincias = cboProvincias;
        m_log.info( "[setCboProvincias] >> Exit" );
    }

    public SelectItem[] getCboDistritos() {
        m_log.info( "[getCboDistritos] << Enter" );
        int iSizeDist = 0;
        TbDistrito dist;
        List<TbDistrito> lstDistritos;


        m_cboDistritos = new SelectItem[ 1 ];
        try {
            if ( m_sProvincia != null && !"000000".equals( m_sProvincia ) ) {
                lstDistritos = CommonDAO.getTbDistritoDAO().loadDistritos( m_sProvincia );
                iSizeDist = lstDistritos.size();
                m_cboDistritos = new SelectItem[ iSizeDist + 1 ];
                for ( int i = 0; i < iSizeDist; i++ ) {
                    dist = lstDistritos.get( i );
                    m_cboDistritos[i + 1] = new SelectItem( dist.getDisCod(), dist.getDisDes() );
                }
            }
        } catch ( Exception ex ) {
            m_log.error( "EX " + ex );
            m_log.error( "EX " + ex.getMessage() );
            ex.printStackTrace();
        } finally {
            if ( iSizeDist == 0 ) {
                m_cboDistritos = new SelectItem[ 1 ];
            }
            m_cboDistritos[0] = new SelectItem( "000000", "[Seleccione Distrito]" );
        }
        m_log.info( "[getCboDistritos] >> Exit" );
        return m_cboDistritos;
    }

    public void setCboDistritos( SelectItem[] cboDistritos ) {
        m_cboDistritos = cboDistritos;
    }

    public String getDepartamento() {
        m_log.info( "[getDepartamento] << Enter" );
        m_log.info( "[getDepartamento] >> Exit" );
        return m_sDepartamento;
    }

    public void setDepartamento( String sDepartamento ) {
        m_log.info( "[setDepartamento] << Enter" );
        m_sDepartamento = sDepartamento;
        m_log.info( "[setDepartamento] >> Exit" );
    }

    public String getProvincia() {
        m_log.info( "[getProvincia] << Enter" );
        m_log.info( "[getProvincia] >> Exit" );
        return m_sProvincia;
    }

    public void setProvincia( String sProvincia ) {
        m_log.info( "[setProvincia] << Enter" );
        m_sProvincia = sProvincia;
        m_log.info( "[setProvincia] >> Exit" );
    }

    //-- ACCIONES
    public void nuevoCliente( ActionEvent event ) {
        m_sDepartamento = "000000";
        m_sProvincia = "000000";
        m_tbCliente = new TbCliente();
        m_sOncomplete = "Richfaces.showModalPanel('mpRegistroClientes');";
    }

    public void editarCliente( ActionEvent event ) {
        int iIdCliente;
        String sUbic;

        iIdCliente = Integer.parseInt( CommonWeb.getParamFromUI( "idCliente" ) );
        m_tbCliente = CommonDAO.getTbClienteDAO().findPorId( iIdCliente );

        if ( m_tbCliente != null ) {
            sUbic = m_tbCliente.getUbicacion();
            if ( sUbic != null && sUbic.length() == 6 && !sUbic.equals( "000000" ) ) {
                m_sDepartamento = sUbic.substring( 0, 2 ) + "0000";
                m_sProvincia = sUbic.substring( 0, 4 ) + "00";
            }
            m_sOncomplete = "Richfaces.showModalPanel('mpRegistroClientes');";
        } else {
            m_sOncomplete = "alert('Error al mostrar al cliente seleccionado.');";
        }
    }

    public void guardarCliente() {
        TbCliente tbCliente;
        try {
            if ( m_tbCliente != null ) {
                tbCliente = CommonDAO.getTbClienteDAO().getClientePorDni( m_tbCliente.getDni() );
                if ( procedeGrabado( tbCliente ) ) {
                    tbCliente = CommonDAO.getTbClienteDAO().getClientePorEmail( m_tbCliente.getEmail() );
                    if ( procedeGrabado( tbCliente ) ) {
                        if ( m_tbCliente.getIdCliente() == null ) {
                            m_tbCliente.setActivo( 1 );
                            CommonDAO.getTbClienteDAO().guardarCliente( m_tbCliente );
                            m_sOncomplete = "javascript:Richfaces.hideModalPanel('mpRegistroClientes');alert('Se guardó correctamente.');";
                        } else {
                            try {
                                CommonDAO.getTbClienteDAO().actualizarCliente( m_tbCliente );
                                m_sOncomplete = "javascript:Richfaces.hideModalPanel('mpRegistroClientes');alert('Se actualizó correctamente.');";
                            } catch ( Exception ex ) {
                                m_sOncomplete = "javascript:Richfaces.hideModalPanel('mpRegistroClientes');alert('Error al actualizar.');";
                            }
                        }
                    } else {
                        m_sOncomplete = "javascript:alert('El EMAIL ya está registrado.');";
                    }
                } else {
                    m_sOncomplete = "javascript:alert('El DNI ya está registrado.');";
                }
            } else {
                m_sOncomplete = "javascript:alert('Error, cliente null');";
            }
        } catch ( Exception ex ) {
            m_log.error( "EX : " + ex );
            m_log.error( "EX : " + ex.getMessage() );
            ex.printStackTrace();
        }
    }

    private boolean procedeGrabado( TbCliente tbCliente ) {
        boolean blFlag = true;
        boolean blIsUpdate;
        int iId;
        int iIdAux;
        blIsUpdate = m_tbCliente.getIdCliente() != null;

        if ( blIsUpdate ) {
            iId = m_tbCliente.getIdCliente().intValue();
            if ( tbCliente != null ) {//Existe DNI
                iIdAux = tbCliente.getIdCliente().intValue();
                if ( iId != iIdAux ) {//Y no es la misma persona
                    blFlag = false;//No se puede repetir DNI
                }
            }
        } else {
            if ( tbCliente != null ) {
                blFlag = false;
            }
        }
        return blFlag;
    }

    public void seleccionarClientePorBorrar( ActionEvent event ) {
        int iIdCliente;
        iIdCliente = Integer.parseInt( CommonWeb.getParamFromUI( "idCliente" ) );
        m_tbCliente = CommonDAO.getTbClienteDAO().findPorId( iIdCliente );
        if ( m_tbCliente != null ) {
            m_sOncomplete = "Richfaces.showModalPanel('mpEliminarCliente');";
        } else {
            m_sOncomplete = "alert('Error al seleccionar cliente.')";
        }
    }

    public void eliminarCliente() {
        int iIdCliente;
        iIdCliente = Integer.parseInt( CommonWeb.getParamFromUI( "idCliente" ) );
        if ( m_tbCliente != null && m_tbCliente.getIdCliente().intValue() == iIdCliente ) {
            m_tbCliente.setActivo( 0 );
            CommonDAO.getTbClienteDAO().actualizarCliente( m_tbCliente );
            m_tbCliente = null;
            m_sOncomplete = "javascript:Richfaces.hideModalPanel('mpEliminarCliente');alert('El cliente se eliminó correctamente.');";
        } else {
            m_sOncomplete = "alert('Error al seleccionar cliente.');";
        }
    }
}
